package com.hangsu.train.components.web.controller;

import com.hangsu.train.components.dto.SecurityRespDto;
import com.hangsu.train.components.entity.Permiss;
import com.hangsu.train.components.entity.User;
import com.hangsu.train.components.params.CodeParam;
import com.hangsu.train.components.params.UserRoleParam;
import com.hangsu.train.components.service.SecurityService;
import com.hangsu.train.components.vo.MenuVo;
import com.hangsu.train.components.vo.UserRoleVo;
import com.hangsu.train.components.web.utils.UserUtils;
import com.hangsu.train.core.result.Resp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lyy
 */
@Slf4j
@RestController
@RequestMapping("/security")
public class SecurityController {

    private SecurityService securityService;

    @Resource
    public void setSecurityService(SecurityService securityService) {
        this.securityService = securityService;
    }

    /**
     * 获取用户菜单
     *
     * @return
     */
    @PostMapping(value = "/user/menus")
    public Resp<List<MenuVo>> menus() {
        User user= UserUtils.getCurrUser();
        List<MenuVo> menus = securityService.getUserMenus(user.getUserCode());
        return Resp.ok(menus);
    }

    /**
     * 获取用户角色
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/user/role")
    public Resp<List<UserRoleVo>> getRoles(@RequestBody @Valid CodeParam param) {
        List<UserRoleVo> respDtos = securityService.getUserRoles(param.getCode());
        return Resp.ok(respDtos);
    }

    /**
     * 用户授权
     *
     * @param param
     */
    @PostMapping(value = "/user/authz")
    public Resp<Object> authorization(@RequestBody @Valid UserRoleParam param) {
        securityService.userAuthz(param.getRoleCodes(), param.getUserCode());
        return Resp.ok();
    }

    /**
     * 获取用户权限列表
     *
     * @param param 用户编码
     * @return Resp<List < PermitsRespDto>> 权限列表
     */
    @PostMapping(value = "/user/permiss")
    public Resp<List<Permiss>> permissions(@RequestBody @Valid CodeParam param) {
        List<Permiss> permissions = securityService.getUserPermiss(param.getCode());
        return Resp.ok(permissions);
    }

    /**
     * 获取用户权限列表
     *
     * @param param 用户编码
     * @return Resp<List < PermitsRespDto>> 权限列表
     */
    @PostMapping(value = "/user/role/permission")
    public Resp<SecurityRespDto> getUserPermission(@RequestBody @Valid CodeParam param) {
        SecurityRespDto respDto = securityService.getUserSecurity(param.getCode());
        return Resp.ok(respDto);
    }

}
